package com.example.a2007dou_shop.login

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.example.a2007dou_shop.R
import com.example.a2007dou_shop.databinding.ActivityLoginBinding
import com.example.a2007dou_shop.mvvm.BaseActivity
import com.example.a2007dou_shop.net.Cons

@Route(path = "/app/LoginActivity")
class LoginActivity : BaseActivity<ActivityLoginBinding,LoginViewModel>() {
    @Autowired
    @JvmField
    var name:String = ""
    @Autowired
    @JvmField
    var pwd:String = ""
    override fun getLayout() = R.layout.activity_login

    override fun getViewModel(): Class<LoginViewModel>  = LoginViewModel::class.java

    override fun initView() {
        ARouter.getInstance().inject(this)
        binding.etName.setText(name)
        binding.etPwd.setText(pwd)
        //登录
        binding.btnLogin.setOnClickListener {
            viewModel.login(binding.etName.text.toString(),binding.etPwd.text.toString())
        }
        binding.goReg.setOnClickListener {
            ARouter.getInstance().build("/app/RegisterActivity").navigation()
        }
        binding.goCode.setOnClickListener {
            ARouter.getInstance().build("/app/LoginCodeActivity").navigation()
        }
        binding.btnLogout.setOnClickListener {
            viewModel.logout()
        }
    }

    override fun initData() {
        viewModel.loginSuccess.observe(this){
            ToastUtils.showLong(it.msg)
            if(it.code==0){
                //跳主页
                Log.d("sss", "initData: ${it.data.toString()}")
                SPUtils.getInstance().put(Cons.SP_TOKEN,it.data.toString())
                ARouter.getInstance().build("/app/MainActivity").navigation()
            }
        }
        viewModel.loginFail.observe(this){
            ToastUtils.showLong(it)
        }
        viewModel.logoutSuccess.observe(this){
            ToastUtils.showLong(it.msg)
            if(it.code==0){
                SPUtils.getInstance().clear()
            }
        }
        viewModel.logoutFail.observe(this){
            ToastUtils.showLong(it)
        }
    }

}